<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/07/19
 * Time: 12:38
 * @link http://www.lmterp.cn
 */

namespace app\command;

use app\common\model\Orders;
use app\common\model\OrdersPickInfo;
use app\common\model\Warehouse;
use app\common\model\WarehouseStock;
use app\common\service\orders\OrderService;
use app\common\service\product\ProductService;
use app\common\service\product\WarehouseService;
use think\console\input\Option;
use think\facade\Log;

/**
 * 订单生成拣货单
 * Class OrderPick
 * @package app\command
 */
class OrderPick extends BaseCommand
{
    protected function configure()
    {
        $this->setName('order_pick')
            ->addOption("pick_qty", null, Option::VALUE_REQUIRED, "每个拣货单上包含多少个订单，默认【100】个")
            ->addOption("warehouse_id", null, Option::VALUE_REQUIRED, "指定仓库id");
    }

    /**
     * 执行生成拣货单
     * @date 2021/07/19
     * @author longli
     */
    protected function handler()
    {
        $pickQty = $this->input->hasOption("pick_qty")
                ? intval($this->input->getOption("pick_qty"))
                : \think\facade\Config::get('param.pick_default_qty', 100);
        $wids = $this->input->hasOption("warehouse_id")
                ? $this->input->getOption("warehouse_id")
                : array_column(Warehouse::getAll()->toArray(), 'warehouse_id');
        if(is_string($wids)) $wids = explode(',', $wids);
        // 已生成拣货单
        $notOrderId = OrdersPickInfo::field("order_id")
            ->where("create_time", "gt", strtotime("-1month"))
            ->order("info_id desc")
            ->column("order_id");

        Log::info('开始生成拣货单');
        // 生成所有仓库的拣货单
        $succ = false;
        foreach($wids as $wid)
        {
            $orders = Orders::field([
                "order_id", "order_sn", "order_no", "warehouse_id", "total_qty"
            ])->with(['detail' => function($query)
            {
                $query->field(["order_id", "sku", "qty", "name_ch", "image_url"]);
            }])->where([
                ["order_status", "eq", Orders::ORDER_DECLARE_SUCC],
                ["stock_status", "eq", WarehouseStock::STOCK_ASSIGN],
                ["track_num", "neq", ""],
                ["warehouse_id", "eq", $wid],
                ["order_id", "not in", $notOrderId],
            ])->select()->toArray();
            foreach(array_chunk($orders, $pickQty) as $tempOrder)
            {
                $succ = true;
                $this->generatePickOrder($wid, $tempOrder);
            }
        }
        Log::info('拣货单生成完成');
        $this->output->write($succ ? 1 : 0);
    }

    /**
     * 生成拣货单
     * @param int $wid 仓库id
     * @param array[] $orders 订单数据
     * @return \app\common\model\OrdersPick|null
     * @date 2021/07/19
     * @author longli
     */
    private function generatePickOrder($wid, $orders)
    {
        // 获取服务类
        $orderService = OrderService::getInstance();
        $pService = ProductService::getInstance();
        $pickData = $pickInfo = [];
        $totalQty = $maxQty = 0;
        foreach($orders as $order)
        {
            // 获取最大数
            if($order['total_qty'] > $maxQty) $maxQty = $order['total_qty'];
            $infoData = [];
            foreach($order['detail'] as $detail)
            {
                $sku = trim($detail['sku']);
                $totalQty += $detail['qty'];
                if(!isset($pickData[$sku]))
                {
                    $pickData[$sku] = $detail;
                    $pickData[$sku]['image_url'] = ProductService::getRootPath($detail['image_url']);
                    $pickData[$sku]['bar_code'] = ProductService::getRootPath($pService->generateBarCode($sku));
                }
                else
                {
                    $pickData[$sku]['qty'] += $detail['qty'];
                }

                // 组装商品数据
                $infoData[] = [
                    "sku" => $sku,
                    "qty" => $detail['qty'],
                    "name_ch" => $detail['name_ch'],
                    "image_url" => $detail['image_url'],
                ];
            }
            $pickInfo[] = [
                "order_id" => $order['order_id'],
                "goods" => $infoData,
            ];
        }
        // 生成拣货单号
        $pickSn = $orderService->generatePickSn();
        // 渲染模板
        $barCode = ProductService::getRootPath($pService->generateBarCode($pickSn, ['show_text' => true, 'font_size' => 20]));
        $html = view('admin@print/orders', [
            'barcode' => $barCode,
            'data' => WarehouseService::getInstance()->sortSkuByWarehouse($wid, array_values($pickData)),
            'total_qty' => $totalQty,
        ])->getContent();
        // 生成 pdf
        $pickPath = $pService->HTML2PDF($html, config('pick_order'), "{$pickSn}.pdf");
        // 写入拣货单
        return $orderService->addPick([
            'pick_sn' => $pickSn,
            'pick_path' => ProductService::hiddenRootPath($pickPath),
            'total_qty' => $totalQty,
            'max_qty' => $maxQty,
        ], $pickInfo);
    }
}
